﻿namespace Leetcode.N0030;
public class Solution
{

    public IList<int> FindSubstring(string s, string[] words)
    {
        var dicWords = this.CreateWordsDic(words);
        var wordLength = words[0].Length;
        var fullLength = wordLength * words.Length;
        var result = new List<int>();
        for (var i = 0; i < wordLength; i += 1)
        {
            for (var j = i; j <= s.Length - fullLength; j += wordLength)
            {
                this.ResetWords(dicWords);
                if (this.TryMatch(s, j, j + fullLength, dicWords, wordLength))
                {
                    result.Add(j);
                }
            }
        }

        return result;
    }

    private bool TryMatch(string s, int from, int to, Dictionary<string, int[]> words, int wordLength)
    {
        for (var i = from; i < to; i += wordLength)
        {
            var word = s.Substring(i, wordLength);
            if (!words.ContainsKey(word))
            {
                return false;
            }
            else
            {
                if (words[word][1] == 0)
                {
                    return false;
                }
                else
                {
                    words[word][1] -= 1;
                }
            }
        }
        return true;
    }

    private Dictionary<string, int[]> CreateWordsDic(string[] words)
    {
        var dic = new Dictionary<string, int[]>();
        for (var i = 0; i < words.Length; i++)
        {
            if (dic.ContainsKey(words[i]))
            {
                dic[words[i]][0] += 1;
            }
            else
            {
                dic.Add(words[i], new int[] { 1, 0 });
            }
        }
        return dic;
    }

    private void ResetWords(Dictionary<string, int[]> words)
    {
        foreach (var item in words)
        {
            item.Value[1] = item.Value[0];
        }
    }
}
